package guoran.red.scanner;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import io.flutter.plugin.common.EventChannel;

public class ScannerBroadcastReceiver extends BroadcastReceiver
    implements EventChannel.StreamHandler {
  private Context context;
  private EventChannel.EventSink events;
  private static final String SM_SCAN_ACTION = "com.sunmi.scanner.ACTION_DATA_CODE_RECEIVED";
  private static final String SM_DATA = "data";
  private static final String ID_SCAN_ACTION = "android.intent.action.SCANRESULT";
  private static final String ID_DATA = "value";
  private static final String XB_SCAN_ACTION = "com.scanner.broadcast";
  private static final String XB_DATA = "data";
  private static final String TELEN_SCAN_ACTION = "my_broadcast_service";
  private static final String TELEN_DATA = "scannerdata";
  private static final String TELEN1_SCAN_ACTION = "com.android.server.scannerservice.broadcast";
  private static final String TELEN1_DATA = "scannerdata";
  public ScannerBroadcastReceiver(Context context) {
    this.context = context;
  }

  @Override
  public void onListen(Object arguments, EventChannel.EventSink events) {
    this.events = events;
    context.registerReceiver(this, new IntentFilter(SM_SCAN_ACTION));
    context.registerReceiver(this, new IntentFilter(ID_SCAN_ACTION));
    context.registerReceiver(this, new IntentFilter(XB_SCAN_ACTION));
    context.registerReceiver(this, new IntentFilter(TELEN_SCAN_ACTION));
    context.registerReceiver(this, new IntentFilter(TELEN1_SCAN_ACTION));
  }

  @Override
  public void onCancel(Object arguments) {
    try {
      context.unregisterReceiver(this);
    } catch (Exception e) {
    }
  }

  @Override
  public void onReceive(Context context, Intent intent) {
    if (events != null) {
      String actionName = intent.getAction();
      if (SM_SCAN_ACTION.equals(actionName)) {
        events.success(intent.getStringExtra(SM_DATA));
      } else if(ID_SCAN_ACTION.equals(actionName)) {
        events.success(intent.getStringExtra(ID_DATA));
      } else if(XB_SCAN_ACTION.equals(actionName)) {
        events.success(intent.getStringExtra(XB_DATA));
      } else if(TELEN_SCAN_ACTION.equals(actionName)) {
        events.success(intent.getStringExtra(TELEN_DATA));
      } else if(TELEN1_SCAN_ACTION.equals(actionName)) {
        events.success(intent.getStringExtra(TELEN1_DATA));
      }
    }
  }
}
